<template>
  <div class="business-signed-plan-list-view view-container">

    <div class="main-content">

      <div class="list-container">

        <div>
          <el-form
            :inline="true"
            :model="formData"
            class="filter-form-inline"
            size="small"
          >
            <el-row
              :gutter="20"
              style="margin-left: 0px;margin-right:0px;"
            >
              <el-col :span="4">
                <el-form-item
                  label="状态"
                  style="width: 100%;"
                >
                  <el-select
                    v-model="formData.planStatus"
                    clearable
                    placeholder="请选择状态"
                    style="width: 100%"
                    @change="onSearch"
                    @clear="onSearch"
                  >
                    <el-option
                      v-for="(item,index) in stateOption"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  label="产品信息"
                  style="width: 100%"
                >
                  <el-select
                    v-model="formData.productId"
                    style="width: 100%"
                    :loading="loading"
                    :remote-method="remoteMethod"
                    clearable
                    filterable
                    placeholder="请选择产品"
                    remote
                    reserve-keyword
                    @change="productChange"
                  >
                    <el-option
                      v-for="item in products"
                      :key="item.id"
                      :label="item.productPopularName"
                      :value="item.id"
                    >
                      {{ item.name }}
                    </el-option>
                  </el-select>

                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  label="规划招商地区"
                  style="width: 100%"
                >
                  <el-cascader
                    ref="cascader"
                    v-model="formData.area"
                    :options="citys"
                    :popper-append-to-body="false"
                    :props="props1"
                    clearable
                    collapse-tags
                    placeholder="请选择地区"
                    style="width: 100%"
                    @change="areaChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  label="关键字"
                  style="width: 100%;"
                >
                  <el-input
                    v-model="formData.selectStr"
                    clearable
                    placeholder="输入规划名称、规划编号查询"
                  >
                    <template
                      v-if="!formData.selectStr"
                      #suffix
                    >
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        content="输入规划名称、规划编号查询"
                        placement="top"
                      >
                        <i class="iconfont icon-wenhao main-color" />
                      </el-tooltip>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <!--
              <el-col :span="2">
                <el-form-item>
                  <more-search-btn v-model:is-more="visible" />
                </el-form-item>
              </el-col>
              -->
              <el-col :span="2">
                <el-form-item style="width:100%;min-width: 170px;">
                  <el-button
                    class="border-btn"
                    icon=""
                    @click="onReast"
                  >重置
                  </el-button>
                  <el-button
                    icon=""
                    type="primary"
                    @click="onSearch"
                  >搜索
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <!--
            <el-row
              v-if="visible"
              :gutter="40"
              style="margin-left: 0px; margin-right: 0px"
            >
              <el-col :span="6">
                <el-form-item
                  label="来源"
                  style="width: 100%;"
                >
                  <el-select
                    v-model="formData.planSource"
                    clearable
                    placeholder="请选择来源"
                    style="width: 100%"
                    @change="onSearch"
                    @clear="onSearch"
                  >
                    <el-option
                      label="直接创建"
                      value="直接创建"
                    />
                    <el-option
                      label="市场准入生成"
                      value="市场准入生成"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="结束日期"
                  style="width: 100%"
                >
                  <date-range-picker
                    v-model:date="formData.endDate"
                    clearable
                    end-placeholder="结束日期"
                    start-placeholder="开始日期"
                    style="width: 100%;"
                    @change="onSearch"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="创建日期"
                  style="width: 100%"
                >
                  <date-range-picker
                    v-model:date="formData.createDate"
                    clearable
                    end-placeholder="结束日期"
                    start-placeholder="开始日期"
                    style="width: 100%;"
                    @change="onSearch"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            -->
          </el-form>
        </div>

        <table-tools>
          <template #left>
            <el-button
              v-auth="{v:['crm:signedPlan:pms']}"
              class="main-btn"
              size="small"
              type="primary"
              @click="addClick"
            >新建
            </el-button>
          </template>

        </table-tools>

        <table-view
          :data="tableData"
          :visible="visible"
          @sort-change="createChange"
          @row-click="rowClick"
        >
          <el-table-column
            :min-width="130"
            align="center"
            fixed="left"
            header-align="center"
            label="招商规划编号"
            prop="planInfo.planNo"
            show-overflow-tooltip
          />
          <el-table-column
            :min-width="250"
            align="left"
            fixed="left"
            header-align="center"
            label="规划名称"
            prop="planInfo.planName"
            show-overflow-tooltip
          />
          <el-table-column
            :min-width="150"
            align="center"
            header-align="center"
            label="商品名"
            prop="planInfo.productName"
            show-overflow-tooltip
          />
          <el-table-column
            :min-width="150"
            align="left"
            header-align="center"
            label="通用名"
            prop="planInfo.productPopularName"
            show-overflow-tooltip
          />
          <el-table-column
            :min-width="100"
            align="center"
            header-align="center"
            label="包装规格"
            prop="planInfo.packSpecs"
            show-overflow-tooltip
          />
          <el-table-column
            :min-width="150"
            header-align="center"
            label="生产厂家"
            prop="planInfo.producer"
            show-overflow-tooltip
          />
          <el-table-column
            :min-width="200"
            header-align="center"
            label="规划招商地区"
          >
            <template #default="scope">
              <areaView :areas="scope.row.planDetail" />
            </template>
          </el-table-column>
          <el-table-column
            :min-width="140"
            align="center"
            header-align="center"
            label="结束日期"
            sortable="custom"
          >
            <template #default="scope">
              {{ dateFormat('yyyy-mm-dd', scope.row.planInfo.expireTime) }}
            </template>
          </el-table-column>
          <!--
          <el-table-column
            :min-width="150"
            align="center"
            header-align="center"
            label="来源"
            prop="planInfo.planSource"
          />
          -->
          <el-table-column
            :min-width="160"
            align="center"
            header-align="center"
            label="创建时间"
            sortable="custom"
          >
            <template #default="scope">
              {{ dateFormat('yyyy-mm-dd HH:MM', scope.row.planInfo.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column
            :min-width="100"
            align="center"
            fixed="right"
            header-align="center"
            label="状态"
          >
            <template #default="scope">
              <div class="tab-line">
                <div>{{ getState(scope.row.planInfo.planStatus) }}</div>
                <div
                  v-if="scope.row.planInfo.flowStatus && scope.row.planInfo.flowStatus=='REJECT_INITIATOR'"
                  class="flow-status-color"
                >
                  [{{ getLabel('approval_result', scope.row.planInfo.flowStatus) }}]
                </div>
              </div>

            </template>
          </el-table-column>
          <el-table-column
            :min-width="200"
            fixed="right"
            header-align="center"
            label="操作"
          >
            <template #default="scope">
              <div v-if="scope.row.planInfo.flowStatus!=='DOING'">
                <el-button
                  v-auth="{v:['crm:signedPlan:pms'],bool:scope.row.planInfo.planStatus == 1 || scope.row.planInfo.planStatus == -1 || scope.row.planInfo.flowStatus=='REJECT_INITIATOR'}"
                  class="delete-text-btn"
                  type="text"
                  @click.stop="onDelete(scope.row)"
                >删除
                </el-button>
                <el-button
                  v-auth="{v:['crm:signedPlan:pms'],bool:scope.row.planInfo.planStatus == 1 || scope.row.planInfo.planStatus == -1 || scope.row.planInfo.flowStatus=='REJECT_INITIATOR'}"
                  type="text"
                  @click.stop="onEdit(scope.row)"
                >编辑
                </el-button>

                <el-button
                  v-auth="{v:['crm:signedPlan:pms'],bool:scope.row.planInfo.planStatus == 1 || scope.row.planInfo.planStatus == -1 || scope.row.planInfo.flowStatus=='REJECT_INITIATOR'}"
                  type="text"
                  @click.stop="onAudit(scope.row)"
                >提交审核
                </el-button>
                <el-button
                  v-auth="{v:['crm:signedPlan:end'],bool:scope.row.planInfo.planStatus == 3}"
                  type="text"
                  @click.stop="onEnd(scope.row)"
                >结束招商
                </el-button>
              </div>

            </template>
          </el-table-column>
        </table-view>

        <Pagination
          v-model:limit="formData.pageSize"
          v-model:page="formData.page"
          :total="total"
          style="display: flex; justify-content: flex-end"
          @pagination="getList"
        />
      </div>

    </div>

  </div>
</template>

<script>
import { useRouter } from 'vue-router'
import {
  defineAsyncComponent,
  defineComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  toRefs,
} from 'vue'
import area from '@/utils/area'
export default defineComponent({
  name: 'Index',
  components: {
    areaView: defineAsyncComponent(() => import('./modules/areaView.vue')),
  },
  setup() {
    const currentInstance = getCurrentInstance()
    const router = useRouter()
    const api = inject('api')
    const citys = area
    const stateOption = reactive([
      {
        label: '审核未通过',
        value: '-1',
      },
      {
        label: '草稿',
        value: '1',
      },
      {
        label: '审核中',
        value: '2',
      },
      {
        label: '进行中',
        value: '3',
      },
      {
        label: '已结束',
        value: '4',
      },
    ])
    const props1 = reactive({
      multiple: true,
      expandTrigger: 'hover',
      label: 'regionName',
      value: 'regionCode',
    })
    var data = reactive({
      loading: false,
      products: [],
      tableData: [],
      cascader: null,
      formData: {
        planType: '2',
        page: 1,
        pageSize: 20,
        planStatus: '',
        selectStr: '',
        planSource: '',
        createDate: [],
        endData: [],
        region: [],
        area: [],
        productId: undefined,
      },
      total: 0,
      visible: false,
      creators: [],
    })

    const getList = () => {
      const a = JSON.parse(JSON.stringify(data.formData))
      if (a.endDate && a.endDate.length) {
        a.expireTimeStart = a.endDate[0]
        a.expireTimeEndTime = a.endDate[1]
      }
      if (a.createDate && a.createDate.length) {
        a.startTime = a.createDate[0]
        a.endTime = a.createDate[1]
      }
      api.plan.GET_PLAN_LIST(a).then((res) => {
        if (res.code) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        } else {
          data.tableData = res.data.list
          data.total = res.data.total
        }
      })
    }

    const addClick = () => {
      router.push({ name: 'signedPlanAdd' })
    }

    const onEdit = (row) => {
      router.push({ name: 'signedPlanAdd', query: { id: row.planInfo.id }})
    }

    const createChange = (obj) => {}

    const onReast = () => {
      data.formData = {
        planType: '2',
        page: 1,
        pageSize: 10,
        planStatus: '',
        selectStr: '',
        planSource: '',
        createDate: [],
        endData: [],
        region: [],
        area: [],
        productId: undefined,
      }
      getList()
    }

    const onSearch = () => {
      data.formData.page = 1
      getList()
    }

    const rowClick = (row, column, event) => {
      if (column.label === '操作') return
      router.push({ name: 'signedPlanDetail', query: { id: row.planInfo.id }})
    }

    const getState = (state) => {
      if (!state) {
        return ''
      }
      switch (state) {
        case '-1':
          return '审核未通过'
        case '1':
          return '草稿'
        case '2':
          return '审核中'
        case '3':
          return '进行中'
        case '4':
          return '已结束'
      }
    }

    const onDelete = (row) => {
      currentInstance.proxy
        .alertBox({
          message: '是否确认删除该规划？',
          title: '删除',
        })
        .then(() => {
          api.plan.PLAN_DELETE_BYID({ id: row.planInfo.id }).then((res) => {
            if (res.code) {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: res.msg,
              })
            } else {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: '删除成功',
              })
              getList()
            }
          })
        })
        .catch((err) => {
          console.log(err)
        })
    }

    const onAudit = (row) => {
      currentInstance.proxy
        .alertBox({
          message: '是否提交审核该规划？',
          title: '审核',
        })
        .then(() => {
          api.plan.PLAN_CHECK_COMMIT({ id: row.planInfo.id }).then((res) => {
            if (res.code) {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: res.msg,
              })
            } else {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: '提交成功',
              })
              getList()
            }
          })
        })
        .catch((err) => {
          console.log(err)
        })
    }

    const onEnd = (row) => {
      currentInstance.proxy
        .alertBox({
          message:
            '结束招商规划后，待开发、开发失败的地区将停止招商，确定结束？',
          title: '结束',
        })
        .then(() => {
          api.plan.PLAN_DETAIL_END({ id: row.planInfo.id }).then((res) => {
            if (res.code) {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: res.msg,
              })
            } else {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: '操作成功',
              })
              getList()
            }
          })
        })
        .catch((err) => {
          console.log(err)
        })
    }

    const areaChange = (val) => {
      const serve = currentInstance.proxy.getServeAreaData(
        val,
        data.cascader.getCheckedNodes()
      )
      data.formData.region = serve
      getList()
    }

    const remoteMethod = (query) => {
      data.products = []
      data.loading = true
      data.searchStr = query

      if (query) {
        const pam = {
          keyWord: query,
        }
        api.common.GET_PRODUCT_LIST(pam).then((res) => {
          if (!res.code && res.data) {
            res.data.list.forEach((a) => {
              a.name = currentInstance.proxy.getProductName(a)
            })
            data.products = res.data.list
          } else {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: res.msg,
            })
          }
          data.loading = false
        })
      } else {
        data.loading = false
      }
    }
    const productChange = (val) => {
      if (!val) {
        data.formData.productId = undefined
      }
      data.formData.page = 1
      getList()
    }

    onMounted(() => {
      getList()
    })

    return {
      ...toRefs(data),
      stateOption,
      citys,
      props1,

      getList,
      rowClick,
      createChange,
      onReast,
      onSearch,
      addClick,
      getState,
      onEdit,
      onDelete,
      onAudit,
      onEnd,
      remoteMethod,
      productChange,
      areaChange,
    }
  },
})
</script>

<style scoped>
</style>
